/*
缓存并发接口函数,解决重复请求和并发请求问题
id：唯一值
cacheSecond:缓存时间,单位秒
syncFunc：加载函数
 */
const _map = {}
const _startTimeMap = {}
const _idArr=[]
const _resArr=[]
const _timeArr=[]
let len=0
let lenMax=3000
async function CacheRequest (syncFunc,id,cacheSecond=0) {
  const now = Date.now()
  const idx=_idArr.indexOf(id)
  if (idx>-1) {
    //在有效时间
    if(now<_timeArr[idx]){
      return _resArr[idx];
    }else{
      _idArr.splice(idx,1)
      _resArr.splice(idx,1)
      _timeArr.splice(idx,1)
      if(len>0){
        len--
      }else{
        len=lenMax
      }
    }
  }
  // 兼容并发加载的情况
  if (!_map[id]) {
    _map[id] = []
    _startTimeMap[id] = now
    const res = await syncFunc()
    //缓存时间
    if(cacheSecond>0){
      _idArr[len]=id
      _resArr[len]=res
      _timeArr[len]=cacheSecond*1000+Date.now()
      len++
      if(len>lenMax){
        len=0
      }
    }
    setTimeout(function () {
      if (_map[id].length > 0) {
        _map[id].forEach(function (callback) {
          callback(res)
        })
      }
      delete _map[id]
      delete _startTimeMap[id]
    }, 0)
    return res
  } else {
    // 10秒超时后，并发不做优化
    if (now - _startTimeMap[id] < 10000) {
      return new Promise(function (resolve) {
        _map[id].push(resolve)
      })
    } else {
      return syncFunc()
    }
  }
}
export default CacheRequest
// module.exports=CacheRequest

// function getUser () {
//   console.log('只会请求一次')
//   return new Promise(function (resolve){
//     setTimeout(function (){
//       resolve({name:'name'})
//     },2000)
//   })
//
// }
// //解决重复请求问题
// async function test1(){
//   const user1=await CacheRequest(getUser,'xx123',3000)
//   const user2=await CacheRequest(getUser,'xx123',3000)
//   const user3=await CacheRequest(getUser,'xx123',3000)
//   console.log('test1',user1,user2,user3)
// }
// test1()
// //解决并发请求问题
// async function test2(){
//   CacheRequest(getUser,'xx123',).then(function (user){
//     console.log('test2',user)
//   })
//   CacheRequest(getUser,'xx123',).then(function (user){
//     console.log('test2',user)
//   })
//   CacheRequest(getUser,'xx123',).then(function (user){
//     console.log('test2',user)
//   })
// }
// test2()